/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
// Copyright tang.  All rights reserved.
// https://gitee.com/inrgihc/dbswitch
//
// Use of this source code is governed by a BSD-style license
//
// Author: tang (inrgihc@126.com)
// Date : 2020/1/2
// Location: beijing , china
/////////////////////////////////////////////////////////////
package com.je.meta.util.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public final class ConnectionUtils {

    private static final int DEFAULT_LOGIN_TIMEOUT_SECONDS = 15;

    /**
     * 建立与数据库的连接
     *
     * @param jdbcUrl  JDBC连接串
     * @param username 用户名
     * @param password 密码
     * @return java.sql.Connection
     */
    public static Connection connect(String jdbcUrl, String username, String password) {
        /*
         * 超时时间设置问题： https://blog.csdn.net/lsunwing/article/details/79461217
         * https://blog.csdn.net/weixin_34405332/article/details/91664781
         */
        try {
            Properties props = new Properties();
            props.put("user", username);
            props.put("password", password);

            /**
             * Oracle在通过jdbc连接的时候需要添加一个参数来设置是否获取注释
             */
            if (jdbcUrl.trim().startsWith("jdbc:oracle:thin:@")) {
                props.put("remarksReporting", "true");
            } else {
                props.setProperty("remarks", "true");
            }
            // 设置最大时间
            DriverManager.setLoginTimeout(DEFAULT_LOGIN_TIMEOUT_SECONDS);

            return DriverManager.getConnection(jdbcUrl, props);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
